import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import pyqtSignal, QObject
import Ui_stewart
import socket
import _thread
import traceback
class myswindow(QMainWindow,Ui_stewart.Ui_MainWindow):  
    def __init__(self):
        super().__init__()#用来继承父类的_init_方法
        self.setupUi(self)
        self.my_thread=My_Thread()
        self.my_thread.sig_nal.connect(self.action)
        
        self.pushButton.clicked.connect(self.button1)
        self.pushButton_2.clicked.connect(self.button2)
    def action(self,text):
        self.textBrowser.setText(text)
    def button1(self): 
        try:
            str=""
            str=str.encode()
            self.my_thread.s.sendall(str)
        except:
            traceback.print_exc()                                                                                                                                                                                                                                              
        self.textBrowser.setText("1")
    def button2(self):
        self.textBrowser.setText("2")  
class My_Thread(QObject):
    sig_nal = pyqtSignal(str)
    port = 9999 #端口号 
    def __init__(self):
        super(My_Thread,self).__init__()
        self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)#创建一个套接字
        self.s.connect(("127.0.0.1",self.port))
        
    def run(self,str):
        self.sig_nal.emit(str) 
    def rec(self):
        while 1: 
            msg = self.s.recv(1024)# 接收小于 1024 字节的数据
            zyj=int.from_bytes(msg,'big',signed=True)
            print(zyj)
            
if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = myswindow() 
    try:
        _thread.start_new_thread(MainWindow.my_thread.rec,())
    except:
        print ("Error: 无法启动线程")
    MainWindow.show()
    sys.exit(app.exec_())
